<template>
  <el-dialog :visible.sync="showDialog" width="30%" :before-close="closeFn">
    <div slot="title" class="dialog-title">
      <span>{{ dialogTitle }}</span>
      <span
        v-if="templateUrl && !staticFileName"
        class="text-red margin-left pointer"
        @click="downloadTemplate"
      >
        下载导入模板
      </span>
      <a
        v-if="staticFileName"
        class="text-red margin-left pointer"
        :href="templateMap[staticFileName]"
      >
        下载导入模板
      </a>
    </div>

    <el-upload
      ref="upload"
      class="upload-demo"
      drag
      :action="actionUrl"
      multiple
      :auto-upload="false"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :file-list="fileList"
      :http-request="uploadFn"
      :before-upload="beforeUpload"
      :on-change="onChange"
    >
      <i class="el-icon-upload" />
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <div v-if="fileType" slot="tip" class="el-upload__tip">
        只能上传{{ fileType === 'img' ? 'jpg/png' : 'excel' }}文件，且不超过50MB
      </div>
      <div v-if="uploadTips" class="margin-top-sm text-grey">
        {{ uploadTips }}
      </div>
      <!-- <el-button slot="trigger" size="small" type="primary">选取文件</el-button> -->
    </el-upload>
    <span slot="footer" class="dialog-footer">
      <el-button @click="closeFn">取 消</el-button>
      <el-button type="primary" @click="submitUpload">上传到服务器</el-button>
    </span>
  </el-dialog>
</template>

<script>
import request from '@/utils/request'

export default {
  name: 'ImportPop',
  props: {
    // 显示弹窗
    uploadDialog: {
      type: Boolean,
      default: false
    },
    // 弹窗标题
    dialogTitle: {
      type: String,
      default: '批量导入'
    },
    // 弹窗提示
    uploadTips: {
      type: String,
      default: ''
    },
    // 是否多选
    isMultiple: {
      type: Boolean,
      default: true
    },
    // 文件类型限制
    fileType: {
      type: String,
      default: ''
    },
    // 下载模板Url
    templateUrl: {
      type: String,
      default: ''
    },
    // 上传Url
    actionUrl: {
      type: String,
      default: '#'
    },
    // 上传Url
    fileName: {
      type: String,
      default: 'templateFile'
    },
    staticFileName: {
      type: String
    },
    waybillId: {
      type: [Number, String]
    }
  },

  data() {
    return {
      fileList: [],
      templateMap: {
        skuInfo: './excel/batch-import-sku-template.xlsx',
        hdClearanceInvoice: './excel/md_li_pa_template.xlsx'
      }
    }
  },
  computed: {
    showDialog: {
      get: function() {
        return this.uploadDialog
      },
      set: function(val) {
        this.$emit(`update:uploadDialog`, val)
      }
    }
  },
  methods: {
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    handlePreview(file) {
      console.log('handlePreview', file)
    },
    onChange(file, fileList) {
      console.log('onChange', file, fileList)
      this.fileList = fileList
    },

    beforeUpload(file, fileList) {
      console.log('beforeUpload-file', file)
      switch (this.fileType) {
        case 'excel':
          const isEXCEL =
            file.type === 'application/vnd.ms-excel' ||
            file.type ===
              'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
          if (!isEXCEL) {
            this.$message.error('上传文件只能是EXCEL文件!')
            return false
          }
          break

        case 'img':
          const isJPG = file.type === 'image/jpeg'
          const isPng = file.type === 'image/png'
          if (!isJPG && !isPng) {
            this.$message.error('上传文件只能是jpg/png文件!')
            return false
          }
          break

        default:
          break
      }

      const isLt50M = file.size / 1024 / 1024 < 50

      if (!isLt50M) {
        this.$message.error('上传文件大小不能超过 50MB!')
        return false
      }

      return true
    },
    closeFn() {
      this.fileList = []
      this.$emit(`update:uploadDialog`, false)
    },
    async uploadFn(params) {
      console.log('params', params)
      // if (!this.beforeUpload(params.file)) return
      const formData = new FormData()
      // 通过 FormData 对象上传文件
      this.formData.append(this.fileName, params.file)
      console.log('this.waybillId :>> ', this.waybillId)
      if (this.waybillId) {
        formData.append('waybillId', this.waybillId)
      }

      this.submitUpload()
    },

    async submitUpload() {
      if (this.fileList.length === 0) {
        this.$message.error('请上传文件')
        return false
      }

      this.$store.dispatch('app/toggleDialog', true)

      const formData = new FormData()
      // 通过 FormData 对象上传文件
      for (const i of this.fileList) {
        if (await this.beforeUpload(i.raw)) {
          formData.append(this.fileName, i.raw)
        }
      }
      if (this.waybillId) {
        formData.append('waybillId', this.waybillId)
      }

      const data = await request({
        url: this.actionUrl,
        method: 'post',
        data: formData,
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
      this.$store.dispatch('app/toggleDialog', false)
      if (data.code === 200) {
        this.$message({
          message: '上传成功！',
          type: 'success'
        })
        // 关闭弹窗
        this.$emit(`update:uploadDialog`, false)
        // 回调
        this.$emit(`uploadCb`, data)
      } else {
        this.$message({
          dangerouslyUseHTMLString: true,
          type: 'error',
          message:
            data.message ||
            data.errorTips ||
            data.formatTips ||
            data.error ||
            '上传失败！'
        })
      }
      this.fileList = []
    },
    downloadTemplate() {
      console.log('downloadTemplate:下载模板')
      window.open('./excel/batch-import-sku-template.xlsx')
    }
  }
}
</script>

<style></style>
